//封装的关于统计的方法
import request from './request'
import {base64Encode,isWeiXinBrower,getCurLanguage} from './base.js'
let L = getCurLanguage
// #ifdef MP-WEIXIN
var amapFile = require('../static/MP-WEIXIN/libs/amap-wx.js');
// #endif
// #ifdef H5
var jweixin = require('../static/h5/jweixin.js'); //引入微信浏览器分享的jssdk
// #endif 
/** 
 * 初始化统计
 * @params showDebug Boolean 是否开启统计日志，默认false 不开启
 * @zjf-2021-06-27
 */

// #ifdef H5
import AMapLoader from '@amap/amap-jsapi-loader';
// #endif

export async function initStat(showDebug = false, initStatCommonProperty) {
	uni.setStorage({
		key: 'sldStatShowDebug',
		data: showDebug,
	});
	let uuid = null
	//获取udid
	if(uni.getStorageSync('sldStatCommonProperty').uuid){
		uuid = uni.getStorageSync('sldStatCommonProperty').uuid
	}else{
		uuid = getUUID();
	}
	// #ifdef MP-WEIXIN
	//获取openid
	let code = await uniLogin();
	let openid = await getOpenid(code)
	uuid = openid;
	// #endif

	//获取位置信息
	initStatCommonProperty = {
		...initStatCommonProperty,
		uuid: uuid,
	}
	updateStatCommonProperty(initStatCommonProperty)
}

/** 
 * 获取微信小程序的code
 * @zjf-2021-06-28
 */
export function uniLogin() {
	let code = '';
	return new Promise(func => {
		uni.login({
			provider: 'weixin',
			success: res => {
				func(res.code)
			},
			fail() {
				func(code)
			}
		})
	})
}

/** 
 * 获取微信小程序的openid
 * @params code String uni.login获取到的code
 * @zjf-2021-06-27
 */
export async function getOpenid(code) {
	let openId = '';
	if (!code) {
		return openId;
	}
	let params = {
		url: 'v3/member/front/login/wechat/getOpenId',
		method: 'POST',
		data: {
			code: code,
			source: 3
		}
	}
	await request(params).then(res => {
		if (res.state == 200) {
			openId = res.data;
		}
	})
	return openId;
}

/** 
 * 设置/更新统计的公共属性
 * @params data Object 要更新的属性数据
 * @zjf-2021-06-27
 */
export function updateStatCommonProperty(data) {
	let target = {};
	try {
		const value = uni.getStorageSync('sldStatCommonProperty');
		if (value) {
			target = value;
		}
	} catch (e) {}
	target = {
		...target,
		...data
	}; //更新或者新增统计的公共属性
	uni.setStorageSync('sldStatCommonProperty', target);
}

/** 
 * 同步获取指定key对应的内容
 * @params key 指定的缓存key
 * @zjf-2021-06-27
 */
export function getStatStorage(key) {
	let target = {};
	try {
		const value = uni.getStorageSync(key);
		if (value) {
			target = value;
		}
	} catch (e) {}
	return target;
}

/** 
 * 获取uuid
 * 如：1624819897644-1389918-0ed8161319cedb-22991203
 * Math.random().toString(16).replace('.', '')：0～1的随机数以十六进制显示，并去掉小数点，如：0.f03fb618bf531，并去掉小数点
 * @zjf-2021-06-27
 */
export function getUUID() {
	return "" + Date.now() + '-' + Math.floor(1e7 * Math.random()) + '-' + Math.random().toString(16).replace('.', '') +
		'-' + String(Math.random() * 31242).replace('.', '').slice(0, 8);
}

/** 
 * 获取地理位置信息,各个终端分别获取
 * @zjf-2021-06-27
 */
export async function getLocation() {
	let locationData = {
		cityCode: '', //城市编码
		cityName: '', //城市名称
		location: '', //经纬度，英文逗号分隔
		provinceCode: '', //	省份编码
		provinceName: '', //	省份名称
	};
	
	// #ifdef H5
	locationData = await getH5Location(locationData);
	// #endif 

	// #ifdef APP-PLUS
	locationData = await getAppLocation(locationData);
	// #endif 

	// #ifdef MP-WEIXIN
	locationData = await getWxXcxLocation(locationData);
	// #endif 

	return locationData;
}

/** 
 * 获取H5的地理位置
 * @zjf-2021-06-28
 */

//初始化高德地图实例
function loadAmap(){
	//自2021年12月02日升级，升级之后所申请的 key 必须配备安全密钥 一起使用
	//配置安全密钥的固定写法
	window._AMapSecurityConfig = {
	    securityJsCode:getApp().globalData.h5GdSecurityCode,
	}
	return new Promise(res=>{
		AMapLoader.load({
			key: getApp().globalData.h5GdKey, // 申请好的Web端开发者Key，首次调用 load 时必填
			// version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
			plugins: ['AMap.Geocoder', 'AMap.Geolocation','AMap.Adaptor'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
		}).then(AMap=>{
			res(AMap)
		}).catch(err=>{
			console.log(err)
		})
	})
}

export function getH5Location(locationData) {
	return new Promise(func => {
		if (!isWeiXinBrower()) {   
			loadAmap().then(AMap=>{
				AMap.plugin('AMap.Geolocation', function () {
					let geolocation = new AMap.Geolocation({
						enableHighAccuracy: false, //是否使用高精度定位，默认:true
						timeout: 15000, //超过15秒后停止定位，默认：无穷大
					});
					geolocation.getCurrentPosition((status, res)=>{
						if(status=='complete'){
							locationData.location = res.position.lng + ',' + res.position.lat;
							if (res.addressComponent&&res.addressComponent.city == '') {
								locationData.provinceName = res.addressComponent.province.substring(0, res.addressComponent.province.length - 1);
								locationData.cityName = res.addressComponent.province;
							}
							func(locationData);
						}else{
							console.info('获取地理位置信息出错，出错信息为：', res);
							func(locationData);
						}
					});
				});
			})
		} else {
			//微信h5获取位置信息
			let tar_url = getApp().globalData.apiUrl + 'v3/member/front/login/wxjsConf?source=1';
			uni.request({
				url: tar_url,
				method: 'GET',
				data: {
					url: encodeURIComponent(location.href)
				},
				success(res) {
					let data = res.data;
					// #ifdef H5
					jweixin.config({
						debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
						appId: data.data.appId, // 必填，公众号的唯一标识
						timestamp: data.data.timestamp, // 必填，生成签名的时间戳
						nonceStr: data.data.nonceStr, // 必填，生成签名的随机串
						signature: data.data.signature, // 必填，签名
						jsApiList: ["getLocation"] // 必填，需要使用的JS接口列表
					});
					jweixin.ready(function() {
						jweixin.getLocation({
							type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
							success: function(res) {
								locationData.location = res.longitude + ',' + res.latitude;
								//根据经纬度获取详细地址信息
								loadAmap().then(AMap=>{
									AMap.plugin('AMap.Geocoder', function () {
										var geocoder = new AMap.Geocoder({
											city: '全国'
										})
										var lnglat = [res.longitude, res.latitude];
										geocoder.getAddress(lnglat, function (status, result) {
											if (status === 'complete' &&result.info === 'OK') {
												let {province,city,adcode} = result.regeocode.addressComponent
												locationData.provinceName =province.substring(0,province.length - 1);
												locationData.cityName =province;
												locationData.adcode = adcode.slice(0,3)
												locationData.cityCode = adcode.slice(0,4)+'00'
												func(locationData);
											} else {
												func(locationData);
											}
										})
									})
								})
							},
							fail(err){
								func(locationData);
							}
						});
					})
					//#endif
				}
			})
		}
	})
}

/** 
 * 获取APP的地理位置
 * @zjf-2021-06-28
 */
export function getAppLocation(locationData) {
	return new Promise(func => {
		uni.getLocation({
			geocode: true,
			success: function(res) {
				locationData.location = res.longitude + ',' + res.latitude;
				locationData.cityName = res.address.city;
				if (res.address&&(res.address.city == res.address.province)) {
					locationData.provinceName = res.address.city.substring(0, res.address.city
						.length - 1);
				}
				func(locationData);
			},
			fail: function(err) {
				console.log('获取位置失败', err)
				func(locationData);
			}
		})
	})
}

/** 
 * 获取微信小程序的地理位置
 * @zjf-2021-06-28
 */

function handleLocationErr(err){
	let title = ''
	switch(err.errCode){
		case "0":{
			title = '定位失败，请打开定位服务后重试'
			break
		}
		
		case "2":{
			title = '定位失败，请打开GPS或wifi后重试'
		}
		
		case "404":{
			title = '定位失败，未获取到定位服务'
		}
	
	}
	
	uni.showToast({
		title,
		icon:'none',
		duration:3000
	})
}



function WxXcxLocation(func,locationData){
	const myAmapFun = new amapFile.AMapWX({
		key: getApp().globalData.WxXcxGdKey
	});
	myAmapFun.getRegeo({
		success: function(data) {
			let {longitude,latitude} = data[0]
			let temp = data[0].regeocodeData.addressComponent;
			locationData.location =`${longitude},${latitude}`;
			if (temp&&(temp.city.length != undefined && temp.city.length ==0)) {
				locationData.provinceName = temp.province.substring(0,
					temp.province.length - 1);
				locationData.cityName = temp.province;
			} else {
				locationData.provinceName = temp.province;
				locationData.cityName = temp.city;
			}
			locationData.adcode = temp.adcode.slice(0,3)
			locationData.cityCode = temp.adcode.slice(0,4)+'00'
			func(locationData)
		}
	})
}
export function getWxXcxLocation(locationData) {
	return new Promise(func => {
		uni.getSetting({
			success: function(res) {
				if (res.authSetting['scope.userFuzzyLocation']) {
					WxXcxLocation(func,locationData)
				} else {
					//初次定位时，延后30秒再定位(针对审核)
					setTimeout(()=>{
						uni.authorize({
							scope: 'scope.userFuzzyLocation',
							success() {
								WxXcxLocation(func,locationData)
							},
							fail(e) {
								handleLocationErr(e)
								func(locationData);
							}
						});
					},30000)
				}
			}
		})
	})
}

/** 
 * 获取设备信息，各个设备分别获取
 * @zjf-2021-06-27
 */
export function getSystemInfo() {
	uni.getSystemInfo({
		"success": function(t) {
			console.info('设备信息：', t);
		},
	})
}

/** 
 * 统计事件
 * @params params Object 参数
 * @zjf-2021-06-27
 */
export async function sldStatEvent(data) {
	// #ifdef MP
	if (!getApp().globalData.allow_privacy && wx.getPrivacySetting) {
		uni.setStorageSync('allow_initStat', JSON.stringify(data));
		return false
	};
	// #endif
	
	//将data和公共属性合并得到最终要发送的数据
	let sldStatCommonProperty = getStatStorage('sldStatCommonProperty');
	let targetParams = {
		...sldStatCommonProperty,
		...data
	};
	
	//没有位置信息的话 要获取位置信息
	if (!targetParams.location) {
		//获取位置信息
		let location = null;
		
		// #ifdef MP||H5
		let first_locate = uni.getStorageSync('first_locate');
		if (!first_locate) {
			location = await getLocation();
			uni.setStorageSync('first_locate',true);
		}
		// #endif
		
		// #ifdef APP-PLUS
		let locate_setting = getApp().globalData.locate_setting
		if(locate_setting!=undefined){
			locate_setting==true&&(location = await getLocation());
		}else{
			locate_setting = await openLocateSetting()
			locate_setting==true&&(location = await getLocation());
			getApp().globalData.locate_setting = locate_setting
		}
		// #endif
		
		targetParams = {
			...targetParams,
			...location
		};
		updateStatCommonProperty(location)
	}
	
	//日志开启的话需要打印数据
	const sldStatShowDebug = uni.getStorageSync('sldStatShowDebug');
	if (sldStatShowDebug) {
		console.info('统计传输数据: ', targetParams);
	}
	
	//发送请求
	let params = {
		url: 'v3/statistics/front/member/behavior/save',
		method: 'POST',
		data: {
			u: base64Encode(JSON.stringify(targetParams))
		}
	}
	
	
	// #ifdef APP-PLUS
	// app端统计接口执行时先判断是否有网
	let networkType = false
	uni.getNetworkType({
		success: (res) => {
			if(res.networkType != 'none'){
				networkType = true
			}
		}
	})
	// networkType为true时说明有网 然后执行接口
	if(networkType){
		request(params).then(res => {})
	}
	// #endif
	
	
	
	
	// #ifndef APP-PLUS
	// 非app端直接调用
	request(params).then(res => {})
	// #endif
}

function openLocateSetting(){
	return new Promise((resolve,reject)=>{
		request({
			url:'v3/system/front/setting/getSettings',
			data:{
				names:'app_apply_market_review'
			}
		}).then(res=>{
			if(res.state==200){
				resolve(res.data[0]!=1)
			}else{
				resolve(false)
			}
		}).catch(err=>{
			reject(false)
		})
	})
}
